package com.xuelang.pipeline.infrastructure.pipeline.repository;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xuelang.pipeline.domain.pipeline.VariableSetting;
import com.xuelang.pipeline.domain.pipeline.repository.VariableSettingRepository;
import com.xuelang.pipeline.infrastructure.pipeline.converter.VariableSettingToDOConverter;
import com.xuelang.pipeline.infrastructure.pipeline.dataobject.VariableSettingDO;
import com.xuelang.pipeline.infrastructure.pipeline.mapper.VariableSettingMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>流水线变量配置仓库接口实现类</p>
 *
 * @author : yixin.lys
 * @date : 2024-06-13 14:03
 **/
@Slf4j
@Service
public class VariableSettingRepositoryImpl implements VariableSettingRepository {
    
    @Autowired
    private VariableSettingMapper mapper;
    
    @Override
    public List<VariableSetting> queryByPipelineCode(String pipelineCode) {
        LambdaQueryWrapper<VariableSettingDO> wrapper = Wrappers.lambdaQuery(VariableSettingDO.class);
        wrapper.eq(StringUtils.isNotBlank(pipelineCode), VariableSettingDO::getPipelineCode, pipelineCode);
        List<VariableSettingDO> found = mapper.selectList(wrapper);
        if (CollectionUtils.isNotEmpty(found)) {
            return found.stream().map(VariableSettingToDOConverter.INSTANCE::fromDO).collect(Collectors.toList());
        }
        return null;
    }

    @Override
    public void addBatch(List<VariableSetting> variableSettingList, String creatorId, Date createTime) {
        mapper.insertBatch(variableSettingList, creatorId, createTime);
    }

    @Override
    public void updateBatch(List<VariableSetting> variableSettingList, String updaterId, Date updateTime) {
        mapper.updateBatch(variableSettingList, updaterId, updateTime);
    }

    @Override
    public void removeByIds(List<Long> idList) {
        mapper.deleteBatchIds(idList);
    }

    @Override
    public void removeByCodes(List<String> codeList) {
        LambdaQueryWrapper<VariableSettingDO> wrapper = Wrappers.lambdaQuery(VariableSettingDO.class);
        wrapper.in(VariableSettingDO::getPipelineCode, codeList);
        mapper.delete(wrapper);
    }

    @Override
    public Boolean batchSaveByPipelineTemplateUuid(String pipelineTemplateUuid, String toPipelineCode, String userId) {
        return mapper.batchInsertByPipelineTemplateUuid(pipelineTemplateUuid, toPipelineCode, userId) >= 0;
    }
}
